const https=require('https');
const http=require('http');
const fs=require('fs');
const path=require('path');
const cheerio=require('cheerio');

http.createServer((req,res)=>{
    var urlStr=req.url;
    if(urlStr=='/'){
        var htmlPath=path.join(__dirname,'/index.html');
        var readable=fs.createReadStream(htmlPath);
        readable.pipe(res);
    }else if(urlStr=='/getlist'){
        var movieId=[];
        var movieName=[];
        var movieOrange=[];
        var movieArr=[];
        https.get('https://maoyan.com/films',(r)=>{
            var content='';
            r.on('data',(chunk)=>{
                content+=chunk;
            })
            r.on('end',()=>{
                content=content.toString();
                // console.log(content);
                var $=cheerio.load(content);
                $('dd').each((index,item)=>{
                    var divArr=$(item).children('div');
                    var aArr=$(divArr[1]).children('a');
                    movieId[index]=$(aArr[0]).attr('data-val').slice(9,-1);
                    movieName[index]=$(aArr[0]).text();
                    var iArr=$(divArr[2]).children('i');
                    movieOrange[index]=$(iArr[0]).text()+$(iArr[1]).text();
                    if(movieOrange[index]==''){
                        movieOrange[index]='暂无评分';
                    }
                    movieObj={
                        movieId:movieId[index],
                        movieName:movieName[index],
                        movieOrange:movieOrange[index]
                    }
                    movieArr[index]=movieObj;
                })
                
                // console.log(movieId);
                // console.log(movieName);
                // console.log(movieOrange);
                movieStr=JSON.stringify(movieArr);
                console.log(movieStr);
                res.end(movieStr);
            })
        })
    }
}).listen(8081);

console.log('server is listening 8081');